package com.wismay.gc.web.dashboard;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springside.modules.mapper.JsonMapper;

import com.wismay.gc.service.dashboard.DataSourceService;

@Controller
@RequestMapping(value = "/webupload")
public class WebuploaderController {
	
	private static Logger logger = LoggerFactory.getLogger(DataSourceController.class);
	private static JsonMapper jsonMapper = JsonMapper.nonDefaultMapper();
	
	@Autowired
	private DataSourceService dataSourceService;
	
	private String allowSuffix = "jpg,png,gif,jpeg";//允许文件格式
    private long allowSize = 20L;//允许文件大小
    private String fileName;
    private String[] fileNames;
     
    public String getAllowSuffix() {
        return allowSuffix;
    }
 
    public void setAllowSuffix(String allowSuffix) {
        this.allowSuffix = allowSuffix;
    }
 
    public long getAllowSize() {
        return allowSize*1024*1024;
    }
 
    public void setAllowSize(long allowSize) {
        this.allowSize = allowSize;
    }
 
    public String getFileName() {
        return fileName;
    }
 
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
 
    public String[] getFileNames() {
        return fileNames;
    }
 
    public void setFileNames(String[] fileNames) {
        this.fileNames = fileNames;
    }
    

    /**
     * 
     * <p class="detail">
     * 功能：重新命名文件
     * </p>
     * @author wangsheng
     * @date 2014年9月25日 
     * @return
     */
    private String getFileNameNew(){
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return fmt.format(new Date());
    }
     
    /**
     * 
     * <p class="detail">
     * 功能：文件上传
     * </p>
     * @author wangsheng
     * @date 2014年9月25日 
     * @param files
     * @param destDir
     * @throws Exception
     */
    public void uploads(MultipartFile[] files, String destDir,HttpServletRequest request) throws Exception {
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
        try {
            fileNames = new String[files.length];
            int index = 0;
            for (MultipartFile file : files) {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
                int length = getAllowSuffix().indexOf(suffix);
                if(length == -1){
                    throw new Exception("请上传允许格式的文件");
                }
                if(file.getSize() > getAllowSize()){
                    throw new Exception("您上传的文件大小已经超出范围");
                }
                String realPath = request.getSession().getServletContext().getRealPath("/");
                File destFile = new File(realPath+destDir);
                if(!destFile.exists()){
                    destFile.mkdirs();
                }
                String fileNameNew = getFileNameNew()+"."+suffix;//
                File f = new File(destFile.getAbsoluteFile()+"\\"+fileNameNew);
                file.transferTo(f);
                f.createNewFile();
                fileNames[index++] =basePath+destDir+fileNameNew;
            }
        } catch (Exception e) {
            throw e;
        }
    }
     
    /**
     * 
     * <p class="detail">
     * 功能：文件上传
     * </p>
     * @author wangsheng
     * @date 2014年9月25日 
     * @param files
     * @param destDir
     * @throws Exception
     */
    public void upload(@RequestParam("file")MultipartFile file, String destDir,HttpServletRequest request) throws Exception {
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
        try {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
                int length = getAllowSuffix().indexOf(suffix);
                if(length == -1){
                    throw new Exception("请上传允许格式的文件");
                }
                if(file.getSize() > getAllowSize()){
                    throw new Exception("您上传的文件大小已经超出范围");
                }
                 
                String realPath = request.getSession().getServletContext().getRealPath("/");
                File destFile = new File(realPath+destDir);
                if(!destFile.exists()){
                    destFile.mkdirs();
                }
                String fileNameNew = getFileNameNew()+"."+suffix;
                File f = new File(destFile.getAbsoluteFile()+"/"+fileNameNew);
                file.transferTo(f);
                f.createNewFile();
                fileName = basePath+destDir+fileNameNew;
        } catch (Exception e) {
            throw e;
        }
    }
    
    @RequestMapping(value = "ajax/upload-dirver-file-for-webuploader/{projectId}", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public String uploadDirverFileForWebuploader(@PathVariable("projectId") Long projectId, @RequestParam("file")MultipartFile file, Model model, HttpServletRequest request) throws Exception {
		logger.info("GET:/data-source/ajax/upload-dirver-file");
		// MultipartFile driverFile = dataSource.getDriverFile();
		logger.info("ContentType:" + file.getContentType());
		logger.info("Name:" + file.getName());
		logger.info("OriginalFilename:" + file.getOriginalFilename());
		logger.info("Size:" + file.getSize());
		
		String backId = request.getParameter("bkeid");
		logger.info("backId:" + backId);

		String ctxDir = request.getSession().getServletContext().getRealPath("");
		logger.info("ctxDir:" + ctxDir);

		dataSourceService.saveDriverFile(projectId, file.getOriginalFilename(), ctxDir, file);

		Map<String, Object> message = new HashMap<String, Object>();
		message.put("result", true);
		message.put("message", "操作成功!");
		return jsonMapper.toJson(message);
	}
    
	
    
}

